from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import FileUtil, MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 癌症相关配置 ==========
CANCER_TYPES = {
    'C34.90': {'name': '肺恶性肿瘤', 'dept': '胸外科', 'symptoms': ['咳嗽', '咯血', '胸痛', '呼吸困难']},
    'C16.9': {'name': '胃恶性肿瘤', 'dept': '胃肠外科', 'symptoms': ['上腹痛', '恶心呕吐', '黑便', '食欲减退']},
    'C18.9': {'name': '结肠恶性肿瘤', 'dept': '胃肠外科', 'symptoms': ['腹痛', '便血', '排便习惯改变', '体重下降']},
    'C50.919': {'name': '乳腺恶性肿瘤', 'dept': '乳腺外科', 'symptoms': ['乳房肿块', '乳头溢液', '皮肤凹陷', '腋窝淋巴结肿大']},
    'C61': {'name': '前列腺恶性肿瘤', 'dept': '泌尿外科', 'symptoms': ['排尿困难', '尿频', '血尿', '骨盆疼痛']}
}

NURSING_ITEMS = {
    'VITAL_SIGNS': [
        {'code': 'VS001', 'name': '体温', 'unit': '℃', 'method': '腋温', 'range': (36.0, 38.0)},
        {'code': 'VS002', 'name': '脉搏', 'unit': '次/分', 'method': '桡动脉触诊', 'range': (60, 100)},
        {'code': 'VS003', 'name': '呼吸', 'unit': '次/分', 'method': '观察', 'range': (12, 20)},
        {'code': 'VS004', 'name': '血压', 'unit': 'mmHg', 'method': '电子血压计', 'range': (90, 140)}
    ],
    'SPECIAL_CARE': [
        {'code': 'SC001', 'name': '疼痛评分', 'unit': '分', 'method': '数字评分法', 'range': (0, 10)},
        {'code': 'SC002', 'name': '血氧饱和度', 'unit': '%', 'method': '指脉氧监测', 'range': (95, 100)},
        {'code': 'SC003', 'name': '血糖', 'unit': 'mmol/L', 'method': '快速血糖仪', 'range': (4.0, 7.8)}
    ]
}


# ========== 生成函数 ==========
def generate_nursing_records():
    sql_statements = []
    record_sn_counter = 40001  # 记录流水号计数器

    # 生成30天的数据
    for day in generate_day_range("2025-08-01", "2025-08-30"):
        records_per_day = 8 if datetime.strptime(day, "%Y-%m-%d").day % 2 else 12

        for i in range(records_per_day):
            # 选择随机癌症类型
            cancer_code, cancer_info = random.choice(list(CANCER_TYPES.items()))

            # 生成患者基本信息
            patient_id = f"PT{random.randint(1000, 9999)}"
            visit_sn = f"VIS{random.randint(1000, 9999)}"
            record_sn = f"NUR{record_sn_counter}"
            record_sn_counter += 1

            # 生成记录时间（每天3-6次护理记录）
            record_time = fake.date_time_between(
                start_date=datetime.strptime(day, "%Y-%m-%d"),
                end_date=datetime.strptime(day, "%Y-%m-%d") + timedelta(days=1)
            )
            test_time = record_time - timedelta(minutes=random.randint(5, 30))

            # 随机选择护理项目（1-3个项目）
            items = []
            items.append(random.choice(NURSING_ITEMS['VITAL_SIGNS']))
            if random.random() < 0.7:  # 70%概率有特殊护理项目
                items.append(random.choice(NURSING_ITEMS['SPECIAL_CARE']))

            # 构建数据字典
            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'medical_record_no': f"MR{random.randint(100000, 999999)}",
                'inpatient_no': f"IP{random.randint(100000, 999999)}",
                'record_sn': record_sn,
                'dept_name': cancer_info['dept'],
                'record_datetime': record_time.strftime('%Y-%m-%d %H:%M:%S'),
                'test_datetime': test_time.strftime('%Y-%m-%d %H:%M:%S'),
                'test_method': items[0]['method'],
                'item_code': items[0]['code'],
                'item_name': items[0]['name'],
                'pain_scores': str(random.randint(0, 5)) if '疼痛评分' in [i['name'] for i in items] else None,
                'item_result_value1': generate_item_result(items[0]),
                'item_result_unit1': items[0]['unit'],
                'item_result_value2': generate_item_result(items[1]) if len(items) > 1 else None,
                'item_result_unit2': items[1]['unit'] if len(items) > 1 else None,
                'record_status': 1,
                'nurse_content': generate_nurse_content(cancer_info['name'], items),
                'yy_upload_status': 0,
                'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_batch_time': day,
                'yy_record_batch_id': f"BATCH{day}_{i}"
            }

            sql = generate_sql('b09_1', data)
            sql_statements.append(sql)

    return sql_statements


def generate_item_result(item):
    """生成护理项目测量结果"""
    if item['name'] == '疼痛评分':
        return str(random.randint(0, 10))
    elif item['name'] == '血氧饱和度':
        return str(random.randint(90, 100))
    elif item['name'] == '血糖':
        return str(round(random.uniform(4.0, 15.0), 1))
    else:  # 生命体征
        if item['name'] == '体温':
            return str(round(random.uniform(item['range'][0], item['range'][1]), 1))
        elif item['name'] == '血压':
            systolic = random.randint(item['range'][0], item['range'][1])
            diastolic = systolic - random.randint(20, 50)
            return f"{systolic}/{diastolic}"
        else:  # 脉搏、呼吸
            return str(random.randint(item['range'][0], item['range'][1]))


def generate_nurse_content(cancer_name, items):
    """生成护理文书内容"""
    content = f"护理记录\n\n患者诊断：{cancer_name}\n"

    # 添加测量结果
    content += "测量结果：\n"
    for item in items:
        result = generate_item_result(item)
        content += f"- {item['name']}: {result}{item['unit']} ({item['method']})\n"

    # 添加护理措施
    nursing_actions = {
        '肺恶性肿瘤': [
            "指导患者有效咳嗽排痰",
            "观察患者呼吸情况",
            "监测血氧饱和度"
        ],
        '胃恶性肿瘤': [
            "观察患者腹部体征",
            "监测胃肠减压量及性状",
            "指导患者饮食管理"
        ],
        '结肠恶性肿瘤': [
            "观察患者排便情况",
            "监测腹部体征",
            "指导患者造瘘口护理"
        ],
        '乳腺恶性肿瘤': [
            "观察患者伤口情况",
            "指导患者患肢功能锻炼",
            "监测引流液性状及量"
        ],
        '前列腺恶性肿瘤': [
            "观察患者排尿情况",
            "监测尿管通畅情况",
            "指导患者膀胱功能训练"
        ]
    }

    content += "\n护理措施：\n"
    for action in random.sample(nursing_actions[cancer_name], 2):
        content += f"- {action}\n"

    # 添加健康教育
    education = {
        '肺恶性肿瘤': "指导患者戒烟，避免呼吸道感染",
        '胃恶性肿瘤': "指导患者少食多餐，避免刺激性食物",
        '结肠恶性肿瘤': "指导患者高蛋白、低渣饮食",
        '乳腺恶性肿瘤': "指导患者患肢功能锻炼方法",
        '前列腺恶性肿瘤': "指导患者盆底肌锻炼方法"
    }
    content += f"\n健康教育：{education[cancer_name]}\n"

    return content


# ========== 辅助函数 ==========
def generate_day_range(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    return [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(delta.days + 1)]


def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成护理记录数据...")
    records = generate_nursing_records()
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b09_1')
    print(f"成功生成{len(records)}条护理记录数据")